package com.example.androidwebview;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.ConsoleMessage;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

/**
 * native call js
 * console.log 输出
 */
public class NativeCallJs_Console extends Activity {
    View btnLoadJs;
    WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.native_call_js);

        //
        webView = (WebView) findViewById(R.id.webView);
        btnLoadJs = findViewById(R.id.btn_load_js);

        //
        webView.loadUrl("file:///android_asset/nativecalljs/index.html");
        webView.getSettings().setJavaScriptEnabled(true);//enable js
        webView.setWebChromeClient(new MyWebChromeClient());//web console
        btnLoadJs.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("---click load js---");

                // 直接调用js中的方法即可
                webView.loadUrl("javascript:sayHello('from Native call js')");
                //更合适的方法是 runJs(str);
                //仍有别的方法调用js 参考cordova nativeToJsxxx
            }
        });
    }

    // 打印 console 日志
    private static class MyWebChromeClient extends WebChromeClient {
        @Override
        public boolean onConsoleMessage(ConsoleMessage cm) {
            Log.d("CONTENT", String.format("%s @ %d: %s", cm.message(), cm.lineNumber(), cm.sourceId()));
            return true;
        }
    }

    // 调用js的方法
    private void runJs(final String jsStr) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                webView.loadUrl(jsStr);
            }
        });
    }
}
